<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加用户按钮 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <div>
            <el-button type="primary" @click="showAddRoleDialog()"
              >添加角色</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-table style="width: 100%" :border="true" :stripe="true" :data="roles">
        <el-table-column width="50" type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 == 0 ? 'bdtop' : '']"
            >
              <!-- 第一级 -->
              <el-col :span="5">
                <el-tag
                  :closable="true"
                  effect="dark"
                  @close="handleClose(item1, scope.row)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 第二、三级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 != 0 ? 'bdtop' : '']"
                >
                  <el-col :span="6">
                    <el-tag
                      :closable="true"
                      effect="dark"
                      type="success"
                      @close="handleClose(item2, scope.row)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 第三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      :closable="true"
                      effect="dark"
                      type="warning"
                      @close="handleClose(item3, scope.row)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" width="50" type="index"> </el-table-column>
        <el-table-column label="角色" width="360" prop="roleName">
        </el-table-column>
        <el-table-column label="角色描述" width="360" prop="roleDesc">
        </el-table-column>
        <el-table-column label="操作" width="360">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="getEditRoleById(scope.row.id)"
              >编辑</el-button
            >

            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteRoleById(scope.row.id)"
              >删除</el-button
            >

            <el-button
              type="warning"
              icon="el-icon-star-off"
              @click="getRights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 增加角色弹窗 -->
    <el-dialog
      title="增加角色"
      :visible.sync="dialogVisibleAdd"
      width="30%"
      @close="addRoleDialogClose()"
    >
      <el-form
        :model="addrolequery"
        :rules="roleRules"
        label-width="80px"
        ref="addroleRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名" v-model="addrolequery.roleName">
          </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input
            placeholder="请输入角色描述"
            v-model="addrolequery.roleDesc"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addrole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色弹窗 -->
    <el-dialog title="修改角色" :visible.sync="dialogVisibleEdit" width="30%">
      <el-form
        :model="editrole"
        :rules="roleRules"
        label-width="80px"
        ref="editroleRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editrole.roleName"> </el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editrole.roleDesc"> </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="editRoleQuery()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="30%"
      @close="resetTree()"
    >
      <el-tree
        :data="rightTree"
        :props="treeprops"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkey"
        ref="treeRef"
      >
      </el-tree>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色
      roles: [],
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      dialogVisible: false,
      roleRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3-5 个字符", trigger: "blur" },
        ],
        roleDesc: [{ required: true, message: "请输入描述", trigger: "blur" }],
      },
      addrolequery: {
        roleName: "",
        roleDesc: "",
      },
      editrole: {},
      rightTree: [],
      treeprops: {
        label: "authName",
        children: "children",
      },
      checkey: [],
      roleid: 1,
    };
  },
  created() {
    this.getroles();
  },
  methods: {
    //   获取角色列表
    async getroles() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取角色列表失败");
      this.roles = res.data;
      // this.$message.success("获取角色列表成功");
    },
    // 显示增加角色弹框
    showAddRoleDialog() {
      this.dialogVisibleAdd = true;
    },
    // 显示修改角色弹框
    showEditDialog() {
      this.dialogVisibleEdit = true;
    },
    // 重置增加角色弹框信息
    addRoleDialogClose() {
      this.$refs.addroleRef.resetFields();
    },
    // 发送增加角色请求
    async addrole() {
      const { data: res } = await this.$http.post("roles", this.addrolequery);
      console.log(res);
      if (res.meta.status != 201) return this.$message.error("创建角色失败");
      this.$message.success("创建角色成功");
      this.dialogVisibleAdd = false;
      this.getroles();
    },
    // 通过id获取角色信息
    async getEditRoleById(editid) {
      const { data: res } = await this.$http.get("roles/" + editid);
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("获取失败");
      // this.$message.success(res.meta.msg);
      this.editrole = res.data;
      this.showEditDialog();
    },
    // 发送修改角色信息请求
    async editRoleQuery() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editrole.roleId,
        {
          roleName: this.editrole.roleName,
          roleDesc: this.editrole.roleDesc,
        }
      );
      console.log(res);
      if (res.meta.status != 200) return this.$message.error("提交失败");
      this.$message.success("修改角色信息成功");
      this.dialogVisibleEdit = false;
      this.getroles();
    },
    // 发送删除角色请求
    deleteRoleById(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          //   if (res.meta.status == 400) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getroles();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //获取权限树
    async getTreeRights() {
      const { data: res } = await this.$http.get("rights/tree");
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取权限列表失败");
      this.rightTree = res.data;
      // this.$message.success("获取权限列表成功");
    },
    getRights(role) {
      this.getTreeRights();
      this.getLeafKeys(role, this.checkey);
      this.roleid = role.id;
      this.dialogVisible = true;
    },
    //获取当前角色拥有权限id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    //重置树
    resetTree() {
      this.checkey = [];
    },
    //分配角色权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleid}/rights`,
        { rids: idStr }
      );
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("分配角色权限失败");
      this.$message.success("分配角色权限成功");
      this.dialogVisible = false;
      this.getroles();
    },
    //删除用户对应权限
    async handleClose(item, row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${row.id}/rights/${item.id}`
          );
          // console.log(res);
          if (res.meta.status !== 200)
            return this.$message.error("删除权限失败");
          this.getroles();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang='less' scoped>
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.el-tag {
  margin: 10px;
}
.el-tag3width {
  width: 20%;
}
</style>